<template>
  <TresObject3D :visible="visible" :position="position">
    <primitive :object="arrowV" :visible="direction === 0" />
    <primitive :object="arrowH" :visible="direction === 1" />
  </TresObject3D>
</template>

<script setup lang="ts">
import * as THREE from 'three'
import { use3DEditorStore, useFormulaEditor } from '@/store'
import { storeToRefs } from 'pinia'

const { isCreating, isEditing } = storeToRefs(use3DEditorStore())
const { hoveredPointer } = storeToRefs(useFormulaEditor())

const arrowH = shallowRef(new THREE.Group())
const arrowV = shallowRef(new THREE.Group())
const position = computed<VerticesType>(() => {
  return hoveredPointer.value?.position || [0, 0, 0]
})
const visible = computed(
  () => !!hoveredPointer.value && !isCreating.value && !isEditing.value,
)
const direction = computed(() => {
  return hoveredPointer.value?.direction || 0
})

// 生成箭头
const createArrow = () => {
  const groupH = new THREE.Group()
  const groupV = new THREE.Group()

  const origin = new THREE.Vector3(0, 0, 0) // 箭头起始点
  const length = 2 // 箭头长度
  const color = 0xff0000 // 箭头颜色
  const headLength = 0.5 // 箭头头部长度
  const headWidth = 0.5 // 箭头头部宽度
  const a = new THREE.ArrowHelper(
    new THREE.Vector3(0, 1, 0),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )
  const b = new THREE.ArrowHelper(
    new THREE.Vector3(1, 0, 0),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )
  const c = new THREE.ArrowHelper(
    new THREE.Vector3(0, -1, 0),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )
  const d = new THREE.ArrowHelper(
    new THREE.Vector3(-1, 0, 0),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )
  const e = new THREE.ArrowHelper(
    new THREE.Vector3(0, 0, 1),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )
  const f = new THREE.ArrowHelper(
    new THREE.Vector3(0, 0, -1),
    origin,
    length,
    color,
    headLength,
    headWidth,
  )

  groupH.add(a, b, c, d)
  groupV.add(e, f)

  arrowH.value = groupH
  arrowV.value = groupV
}

onMounted(() => {
  createArrow()
})
</script>

<style scoped lang="scss"></style>
